package com.interview.javac;



import javax.tools.*;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.List;

import static javax.tools.StandardLocation.CLASS_OUTPUT;
import static javax.tools.StandardLocation.CLASS_PATH;

public class CompileAnnotationString {

	public static void main(String[] args) throws IOException {
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

		DiagnosticCollector<JavaFileObject> diagnostics =
				new DiagnosticCollector<>();
		StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
		JavaStringObject stringObject =
				new JavaStringObject("Test.java", getSource());

		String classes = System.getProperty("user.dir")+"/compile/javac/target/classes";
		File classesFile = new File(classes);
		fileManager.setLocation(CLASS_OUTPUT,Arrays.asList(classesFile));

//		String classPath = System.getProperty("java.class.path")+":"+"/Users/lijiazhi/Library/Java/JavaVirtualMachines/corretto-1.8.0_322/Contents/Home/lib/tools.jar";
//		List<String> options = Arrays.asList("-classpath", classPath);


		JavaCompiler.CompilationTask task = compiler.getTask(null,
				fileManager, diagnostics, null, null, Arrays.asList(stringObject));

		boolean success = task.call();
		System.out.println(success?"编译成功":"编译失败");
		diagnostics.getDiagnostics().forEach(System.out::println);


	}

	/**
	 * 编译后，Test变成final
	 * @return
	 */
	public static String getSource() {
		return "package spring;import com.interview.processor.Tool; "
				+ "@Tool "
				+ "public class Test  {"
				+ "  public  static void doSomething(String v){"
				+ "     int a = 1;"
				+ "  }"
				+ "}";
	}
}

